<template>
    <div class="login">
        <el-card class="box-card">
            <div class="login-title">登录</div>
            <el-form ref="ruleFormRef" :model="userForm" status-icon :rules="rules" label-width="100px"
                class="demo-ruleForm">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="userForm.userName" type="text" autocomplete="off" />
                </el-form-item>
                <el-form-item label="密码" prop="pass">
                    <el-input v-model="userForm.pass" type="password" autocomplete="off" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { login } from '@/api/user'
import router from "@/router";
import { ElMessage } from 'element-plus'

const ruleFormRef = ref<FormInstance>()

const validateUserName = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入用户名'))
    } else {
        callback()
    }
}

const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else {
        callback()
    }
}


const userForm = reactive({
    userName: '',
    pass: '',
})

const rules = reactive<FormRules<typeof userForm>>({
    userName: [{ validator: validateUserName, trigger: 'blur' }],
    pass: [{ validator: validatePass, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            login(userForm.userName, userForm.pass).then((result) => {
                if (result.status == 200) {
                    localStorage.setItem('token', result.data.access)
                    ElMessage.success('登录成功')
                    router.push('/')
                } else {
                    ElMessage.error('登录失败')
                    formEl.resetFields()
                }
            })
            console.log('submit!')
        } else {
            console.log('error submit!')
            return false
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>
<style scoped>
.login {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.text {
    font-size: 14px;
}

.item {
    padding: 18px 0;
}

.box-card {
    width: 480px;
}

.box-card .login-title {
    font-size: 25px;
    padding: 18px 0;
    display: block;
    text-align: center;
}
</style>
  